package net.lesscoding.kafka.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

import static net.lesscoding.kafka.common.Const.OS_KAFKA;

/**
 * @author eleven
 * @date 2024/6/29 16:10
 * @apiNote
 */
public class KafkaConsumerTest {
    public static void main(String[] args) {
        // 1. 创建消费者对象
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, OS_KAFKA);
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "test");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);
        // 2. 订阅主题
        consumer.subscribe(Collections.singletonList("test"));
        // 3. 从Kafka中拉取数据
        while (true) {
            ConsumerRecords<String, String> pollDataList = consumer.poll(Duration.ofMillis(100));
            for (ConsumerRecord<String, String> data : pollDataList) {
                System.out.println(data);
            }
        }
        // 3. 关闭消费者对象
        //consumer.close();

    }
}
